import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:message_tools/components/index.dart';
import 'package:message_tools/store/index.dart';
import 'package:message_tools/store/view_model/index.dart';
import 'package:sms/sms.dart';

const buttonHeight = 50.0;
const rightButtonHeight = 40.0;

class SmsReSendPage extends StatefulWidget {
  int sendStatus;

  SmsReSendPage(this.sendStatus);

  @override
  _SmsReSendPagePageState createState() => _SmsReSendPagePageState();
}

class _SmsReSendPagePageState extends State<SmsReSendPage> {
  TextEditingController _intervalCtrl = new TextEditingController();
  String _statusText;
  Color _statusTextColor;
  int _sendSuccessNum;
  int _sendFailNum;
  int _sendNum;
  int _totalSmsNum;
  String _progess;
  Color _startBtnBackgroundColor;
  Color _startBtnForegroundColor;
  String _startBtnContent;
  String _previewContent;

  bool _isCancel;
  SmsSender _smsSender = new SmsSender();

  double percentage = 0.0;

  @override
  void initState() {
    _progess = "0.00";
    _sendSuccessNum = 0;
    _sendFailNum = 0;
    _sendNum = 0;
    _totalSmsNum = 0;
    _statusText = "未开始";
    _statusTextColor = Colors.red;
    _intervalCtrl.text = "3";
    _startBtnContent = "开始";
    _previewContent = "";
    _startBtnBackgroundColor = Colors.green;
    _startBtnForegroundColor = Colors.white;
    _isCancel = false;
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarPlugin.Create("执行任务", centerTitle: true,
          leading: Builder(builder: (BuildContext c) {
        return IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            });
      })),
      body: Theme.of(context).platform == TargetPlatform.iOS
          ? CupertinoScrollbar(
              child: _buildBody(),
            )
          : Scrollbar(
              child: _buildBody(),
            ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
        child: Column(
      children: <Widget>[
        createTitleView(),
        createSendInterval(),
        createTaskButtons(),
        createTaskStatus(),
        createTaskProgess(),
        createRunTaskResult(),
        createPreviewMessage(),
      ],
    ));
  }

  Container createTitleView() {
    return Container(
        child: Row(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.only(left: 5, top: 5),
          alignment: Alignment.center,
          child: Text("任务名称: "),
        ),
        Container(
          padding: const EdgeInsets.only(left: 5, top: 5),
          alignment: Alignment.center,
          child: Text(""),
        ),
      ],
    ));
  }

  Row createSendInterval() {
    return Row(children: <Widget>[
      Container(
        padding: const EdgeInsets.only(left: 5, top: 5),
        alignment: Alignment.center,
        child: Text("每条短信发送间隔:"),
      ),
      Expanded(
        child: TextField(
          textAlign: TextAlign.center,
          controller: _intervalCtrl,
        ),
      ),
      Container(
        padding: const EdgeInsets.only(left: 5, top: 5),
        alignment: Alignment.center,
        child: Text("秒(1-120)"),
      ),
      Expanded(child: Text("")),
      Expanded(child: Text("")),
    ]);
  }

  Row createTaskButtons() {
    return Row(
      children: <Widget>[
        Expanded(
          child: Container(
              padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
              alignment: Alignment.center,
              child: createButton(
                  height: buttonHeight,
                  text: "$_startBtnContent",
                  minWidth: double.infinity,
                  backgroundColor: _startBtnBackgroundColor,
                  textColor: _startBtnForegroundColor,
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                  onPressed: () async {
                    if (_statusText == "执行中..." ||
                        _statusText == "已完成" ||
                        _statusText == "任务已结束") {
                      mAlertDialog(context, "任务$_statusText");
                      return;
                    }

                    setState(() {
                      _statusText = "执行中...";
                      _statusTextColor = Colors.red;
                      _startBtnContent = _statusText;
                      _startBtnBackgroundColor = Colors.grey;
                      _startBtnForegroundColor = Colors.white;
                    });

                    var store = Store.value<SmsSendRecordModel>(context);

                    // 根据状态获取数量
                    var total = await store.getSendCount(widget.sendStatus);

                    int limit = 100;
                    int page = (total / limit).ceil();

                    setState(() {
                      _totalSmsNum = total;
                    });

                    for (int pageindex = 0; pageindex < page; pageindex++) {
                      int offset = pageindex * limit;
                      var list = await store.getDataList(
                          widget.sendStatus, offset, limit);

                      for (int i = 0; i < list.length; i++) {
                        var smsSendRecord = list[i];
                        if (smsSendRecord.content.trim() == "") {
                          continue;
                        }

                        if (_isCancel) {
                          break;
                        }

                        setState(() {
                          _previewContent = smsSendRecord.content;
                        });
                        await sendMessage(smsSendRecord.nindex,
                            smsSendRecord.phoneNum, smsSendRecord.content);
                      }

                      if (_isCancel) return;

                      setState(() {
                        _statusText = "已完成";
                        _statusTextColor = Colors.green;
                        _startBtnContent = _statusText;
                        _startBtnBackgroundColor = Colors.grey;
                        _startBtnForegroundColor = Colors.black;
                      });
                    }
                  })),
        ),
        Expanded(
          child: Container(
              padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
              alignment: Alignment.center,
              child: createButton(
                  height: buttonHeight,
                  text: "结束",
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  minWidth: double.infinity,
                  backgroundColor: Colors.red,
                  onPressed: () {
                    setState(() {
                      _isCancel = true;
                      _statusText = "任务已结束";
                      _statusTextColor = Colors.red;
                      _startBtnContent = _statusText;
                      _startBtnBackgroundColor = Colors.grey;
                      _startBtnForegroundColor = Colors.white;
                    });
                  })),
        )
      ],
    );
  }

  sendMessage(String nindex, String phoneNum, String smsContent) async {
    var store = Store.value<SmsSendRecordModel>(context);
    SmsMessage message = new SmsMessage(phoneNum, smsContent);
    message.onStateChanged.listen((state) {
      debugPrint("state = $state \n");
      if (state == SmsMessageState.Delivered) {
        setState(() {
          _sendSuccessNum++;
          // 发送成功
          store.updateSmsRecordStatus(message.toMap["address"], 2);
        });
      } else if (state == SmsMessageState.Fail) {
        setState(() {
          _sendFailNum++;
          // 发送失败
          store.updateSmsRecordStatus(message.toMap["address"], 3);
        });
      }
    });

    Duration interval = Duration(seconds: int.parse(_intervalCtrl.text));
    Stream<int> stream = Stream.periodic(interval, (data) => data);
    await stream.take(1).forEach((_) {
      _smsSender.sendSms(message);
      setState(() {
        _sendNum++;
        _progess = ((_sendNum.toDouble() / _totalSmsNum.toDouble()) * 100)
            .toStringAsFixed(2);
        // 已发送
        store.updateSmsRecordStatus(message.toMap["address"], 1);
      });
    });
  }

  Future<String> Sleep() {
    return Future<String>(() {
      sleep(Duration(seconds: int.parse(_intervalCtrl.text)));
      return "";
    });
  }

  Row createProgressIndicator() {
    return Row(
      children: <Widget>[],
    );
  }

  Row createTaskStatus() {
    return Row(
      children: <Widget>[
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text("任务状态: ")),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "$_statusText",
              style: TextStyle(
                  color: _statusTextColor, fontWeight: FontWeight.bold),
            )),
      ],
    );
  }

  Row createTaskProgess() {
    return Row(
      children: <Widget>[
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "任务进度: ",
            )),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "$_progess%",
              style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
            )),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "已发送: ",
            )),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "$_sendNum",
              style:
                  TextStyle(color: Colors.green, fontWeight: FontWeight.bold),
            )),
      ],
    );
  }

  Row createRunTaskResult() {
    return Row(
      children: <Widget>[
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "发送成功: ",
            )),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "$_sendSuccessNum      ",
              style:
                  TextStyle(color: Colors.green, fontWeight: FontWeight.bold),
            )),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "发送失败: ",
            )),
        Container(
            padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
            alignment: Alignment.center,
            child: Text(
              "$_sendFailNum",
              style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
            )),
      ],
    );
  }

  Container createPreviewMessage() {
    return Container(
        //margin: new EdgeInsets.all(5),
        width: double.infinity,
        padding: new EdgeInsets.all(40),
        decoration: new BoxDecoration(
            /*color: Color(0xFFebebf3),
                borderRadius: new BorderRadius.circular(10.0)),*/
            image: DecorationImage(
          image: AssetImage("assets/images/sms_bg.png"),
          fit: BoxFit.fill,
        )),
        child: new LimitedBox(
          maxWidth: MediaQuery.of(context).size.width,
          child: Text("$_previewContent",
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              maxLines: 100,
              textAlign: TextAlign.left,
              style: new TextStyle(height: 1, fontSize: 20)),
        ));
  }

  void mAlertDialog(BuildContext context, String content) {
    showDialog(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('系统提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
          elevation: 20,
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        );
      },
    );
  }
}
